const util = require("../../utils/util");
Page({
/**
   * 页面的初始数据
   */
  data: {
    detail: {},
    place_id: "",
    price: 0,
    totalNum: 1,
    // 预订人信息
    preUserInfo: {
      name: "",
      phone: "",
      email: "",
      remarks: ""
    },
    // 随行人信息
    userTogether: [],
    show: false,
    isFocus: false, //控制input 聚焦
    wallets_password_flag: false//密码输入遮罩
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      price: options.price * 1,
      place_id: options.id
    })
    this.getDetail(options.id);
  },
  /**获取门票详情 */
  getDetail(id) {
    wx.$http.post(wx.$api.fetchTouristDetail, {id}).then(res => {
      this.setData({
        detail: res
      })
  })
  .catch(err => {
    wx.showToast({
      title: '系统异常',
    })
  })
  },
  onChangePrice(e) {
    let num = e.detail;
    let userTogether = this.data.userTogether;
    if(num > userTogether.length + 1) {
      userTogether.push({name: "", phone: ""});
    } else {
      userTogether.pop()
    }

    this.setData({
      userTogether,
      totalNum: num
    })
  },
  // 获取联系人姓名
  bindContactName(e) {
    let type = e.target.dataset.type;
    let index = e.target.dataset.index;
    if(type === "together") {
      this.data.userTogether[index].name = e.detail.value;
    } else {
      this.data.preUserInfo.name = e.detail.value;
    }
  },
  // 获取联系人号码
  bindContactPhone(e) {
    let type = e.target.dataset.type;
    let index = e.target.dataset.index;
    let value = e.detail.value;
    if(type === "together") {
      this.data.userTogether[index].phone = value;
    } else {
      this.data.preUserInfo.phone = value;
    }
  },
  // 获取电子邮箱
  bindContactEmail(e) {
    this.data.preUserInfo.email = e.detail.value;
  },
  // 获取备注信息
  bindContactRemarks(e) {
    this.data.preUserInfo.remarks = e.detail.value;
  },
  /**去支付 */
  goToPay() {
    console.log("验证过1");
    if(!this.data.preUserInfo.name) {
      return wx.showToast({title: "请输入预订人姓名！", icon: "none"});
    }
    console.log("验证过2");
    if(!this.data.preUserInfo.phone) {
      return wx.showToast({title: "请输入预订人手机号！", icon: "none"});
    }
    console.log("验证过3");
    let isComplete = this.data.userTogether.every(item => {
      return item.phone && item.name;
    })
    console.log("验证过4");
    if(!isComplete) {
      return wx.showToast({title: "请完善随行人信息！", icon: "none"});
    }
    console.log("验证通过");
    this.setData({
      show: true
    })
    
  },
  closePasswordDia() {
    this.setData({
      show: false
    })
  },
  //获取钱包密码
  set_wallets_password (e) {
    this.setData({
     wallets_password: e.detail.value
    });
    //密码长度6位时，自动验证钱包支付结果
    if (this.data.wallets_password.length == 6) {
      this.saveOrder();
    }
   },
   // 保存订单信息
   saveOrder() {
     let params = {
      place_id: this.data.place_id,
      self: this.data.preUserInfo,
      other: this.data.userTogether,
      total_price: this.data.price * this.data.totalNum
     }
    wx.$http.post(wx.$api.fetchOrderCreate, params).then(res => {
      console.log(res);
      wx.showToast({
        title: '购买成功',
      })
      this.setData({
        show: false
      })
      wx.switchTab({
        url: '/pages/dingdan/dingdan',
      })
    })
    .catch(err => {
      wx.showToast({
        title: '购买失败',
      })
    })
   },
   //聚焦input
   set_Focus () {
    console.log('isFocus', this.data.isFocus)
    this.setData({
     isFocus: true
    })
   },
   set_notFocus () {//失去焦点
    this.setData({
     isFocus: false
    })
   },
   close_wallets_password () {//关闭钱包输入密码遮罩
    this.setData({
     isFocus: false,//失去焦点
     wallets_password_flag: false,
    })
   },
   // 门票购买
   uploadImg() {
    const cos = util.getUploadToken();
    // 先选择文件，得到临时路径
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original'], // 可以指定是原图还是压缩图，默认用原图
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
            var filePath = res.tempFiles[0].path;
            var filename = filePath.substr(filePath.lastIndexOf('/') + 1);
            cos.postObject({
                Bucket: 'feng-1300275634',
                Region: 'ap-chengdu',
                Key: 'test/' + filename,
                FilePath: filePath,
                onProgress: function (info) {
                    console.log(JSON.stringify(info));
                }
            }, function (err, data) {
              if(err) {
                console.log("错误")
              } else {
                console.log(data)
              }
            });
        }
      });
   }
})